<template>
  <uni-popup ref="popupRef" type="center" :is-mask-click="false" closeable>
    <view class="popup"
      ><uni-forms
        :modelValue="formData"
        :rules="rules"
        label-align="right"
        ref="formRef"
      >
        <uni-forms-item label="名称" name="name" required>
          <uni-easyinput
            type="text"
            v-model="formData.name"
            placeholder="请输入分类名称"
          />
        </uni-forms-item>
        <uni-forms-item label="排序" name="sort">
          <uni-easyinput
            type="number"
            v-model.number="formData.sort"
            placeholder="请输入排序"
          />
        </uni-forms-item>
        <uni-forms-item label="缩略图" name="thumb">
          <select-one-img :formData="formData" @update:formData="handleUpdateFormData" :width="100" ratio="9/16" />
        </uni-forms-item>
        <uni-forms-item label="是否推荐" name="isRecommend">
          <switch
            :checked="formData.select"
            @change="handleSelectChange"
            class="switch-btn"
          />
        </uni-forms-item>
        <uni-forms-item label="是否启用" name="isEnable">
          <switch
            @change="handleEnableChange"
            :checked="formData.enable"
            class="switch-btn"
          />
        </uni-forms-item>
        <uni-forms-item>
          <view class="operate-btn">
            <button type="primary" size="mini" @click="handleSave">保存</button>
            <button type="warn" size="mini" @click="cancel">取消</button>
          </view>
        </uni-forms-item>
      </uni-forms></view
    >
  </uni-popup>
  
</template>
<script setup>
import { ref,nextTick } from 'vue';
import { cloudToHttp } from '@/utils/tools';
import { showToast ,uploadFile} from '@/utils/common';
import selectOneImg from '@/components/select-one-img/select-one-img.vue';

const props = defineProps({
  type: {
    type: String,
    default: 'add',
  },
  maxSort: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits(['init']);
const classifyCloudObj = uniCloud.importObject('admin-bizhi-classify', {
  customUI: true,
});
const popupRef = ref(null);
const formData = ref({
  name: '',
  sort: 0,
  select: false,
  enable: false,
  picurl: '',
  tempurl: '',
});
const formRef = ref(null);
const open = (item) => {
  popupRef.value.open();

  if (props.type == 'edit') {
    formData.value = item;
    formData.value.tempurl = item.picurl;
  }else{

    nextTick(() => {
      formData.value.sort = props.maxSort + 1;
    });
  }
};

const rules = ref({
  name: {
    rules: [
      { required: true, errorMessage: '请输入分类名称' },
      {
        minLength: 2,
        maxlength: 8,
        errorMessage: '分类名称至少2个字符，最多8个字符',
      },
    ],
  },
});
const handleSave = async () => {
  try {
    uni.showLoading({
      title: '保存中...',
      mask: true,
    });
    await formRef.value.validate();
    if (formData.value.tempurl && formData.value.tempurl != formData.value.picurl) {
      let file = await uploadFile(formData.value.tempurl);
      formData.value.picurl = cloudToHttp(file.fileID);
    }
    let params = { ...formData.value };
    delete params.tempurl;
    const { errCode, errMsg } =
      props.type == 'add'
        ? await classifyCloudObj.add(params)
        : await classifyCloudObj.update(params);

    if (errCode == 0) {
      showToast({
        title: props.type == 'add' ? '添加成功' : '修改成功',
      });
      popupRef.value.close();
      setTimeout(() => {
        init();
        emit('init');
      }, 1000);
    } else {
      showToast({
        title: errMsg,
      });
    }
  } catch (err) {
    showToast({
      title: err,
    });
  } finally {
    uni.hideLoading();
  }
};



const handleSelectChange = (e) => {
  formData.value.select = e.detail.value;
};
const handleEnableChange = (e) => {
  formData.value.enable = e.detail.value;
};
const selectPic = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    success: (res) => {
      formData.value.tempurl = res.tempFilePaths[0];
    },
  });
};


const init = () => {
  formData.value = {
    name: '',
    sort: 0,
    select: false,
    enable: false,
    picurl: '',
    tempurl: '',
  };
};

const cancel = () => {
  popupRef.value.close();
  init();
};


const handleUpdateFormData = (newFormData) => {
  formData.value = newFormData;
};
defineExpose({
  open,
  init,
});
</script>

<style lang="less" scoped>
.popup {
  background-color: #fff;
  width: 600px;
  min-height: 200px;
  padding: 30px;
  border-radius: 10px;
 
}
.btnGroup {
    display: flex;
    margin: 0;
    gap: 30px;
    padding: 50px 0;
    button {
      width: 200px;
    }
  }
</style>
